//
//  NetworkManager.m
//  BaseLib
//
//  Created by CPX on 2018/5/21.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "NetworkManagerV3.h"
#import "AFNetworking.h"
#import "AFHTTPSessionManager+Helper.h"

#define NetworkTimeOutIntervel 20

//NSErrorDomain const EgddErrorDomin = @"app.response.failure";
//NSInteger const AppResponseFailureCode = 1;
//NSString *const AppResponseFailureText = @"Reqest Failure";

/**
 网络库封装V3
 @author yzl
 */
@implementation NetworkManagerV3

+ (instancetype)sharedManager{
    static NetworkManagerV3 *mgr;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mgr = [NetworkManagerV3 new];
    });
    return mgr;
}

+ (void)GETWithURL:(NSString *)url params:(NSDictionary *)params success:(Success)success failure:(Failure)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = NetworkTimeOutIntervel;
    
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
        
    }];
}

+ (void)GETWithURL:(NSString *)url header:(NSDictionary *)headers params:(NSDictionary *)params success:(Success)success failure:(Failure)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = NetworkTimeOutIntervel;
    for (NSString *key in headers.allKeys) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
        
    }];
}

+ (void)GETWithURL:(NSString *)url header:(NSDictionary *)headers params:(NSDictionary *)params success:(Success)success failure:(Failure)failure name:(NSString *)name{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = NetworkTimeOutIntervel;
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    for (NSString *key in headers.allKeys) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    
    NSURLSessionDataTask *task = [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[NetworkManagerV3 sharedManager].keyForTask removeObjectForKey:name];
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -999) {
            return ;
        }
        [[NetworkManagerV3 sharedManager].keyForTask removeObjectForKey:name];
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
        
    }];
    [NetworkManagerV3 sharedManager].keyForTask[name] = task;
}

+ (void)PUTWithURL:(NSString *)url header:(NSDictionary *)headers params:(NSDictionary *)params success:(Success)success failure:(Failure)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = NetworkTimeOutIntervel;
    for (NSString *key in headers.allKeys) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    
    [manager PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
    }];
    
}

+ (void)PUTWithURL:(NSString *)url header:(NSDictionary *)headers params:(NSDictionary *)params formParams:(NSDictionary*)formParams success:(Success)success failure:(Failure)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = NetworkTimeOutIntervel;
    for (NSString *key in headers.allKeys) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    
    [manager PUT:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formParams enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [formData appendPartWithFileData:obj name:key fileName:[key stringByAppendingString:@".jpeg"] mimeType:@"image/jpeg"]; //

        }];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
    }];
    
}

+ (void)GETWithURL:(NSString *)url params:(NSDictionary *)params progress:(DownloadProgress)progress success:(Success)success failure:(Failure)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = 20;
    
    [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"ok");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
    }];
}

+ (void)GETWithURL:(NSString *)url header:(NSDictionary*)headers params:(NSDictionary *)params  progress:(DownloadProgress)progress success:(Success)success failure:(Failure)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = 20;
    for (NSString *key in headers.allKeys) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"ok");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
    }];
}

+ (void)POSTWithURL:(NSString *)url params:(id)params success:(Success)success failure:(Failure)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = NetworkTimeOutIntervel;
    
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
        
    }];
}

+ (void)POSTWithURL:(NSString *)url header:(NSDictionary*)headers params:(id)params success:(Success)success failure:(Failure)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 20;
    for (NSString *key in headers.allKeys) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if (!data) {
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:@{@"msg":error.userInfo[@"NSLocalizedDescription"]}];
            failure(error1);
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (dic) {
            success(dic);
        }
        else{
            NSError *error1 = [NSError errorWithDomain:@"app_response_error" code:10001 userInfo:dic?dic:@{@"msg":@"Unknow Error"}];
            failure(error1);
        }
        
    }];
}

+ (void)DownloadFile:(NSString *)url progress:(DownloadProgress)progress destination:(Destination)destination completionHandler:(CompletionHandler)completion name:(NSString*)name{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSURLSessionDownloadTask *downloadTask =  [manager downloadTaskWithRequest:request progress:progress destination:destination completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        completion(response,filePath,error);
        
    }];
    
    [downloadTask resume];
}

- (void)startMonitoring{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

- (void)stopMonitoring{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}

- (void)cancelTask:(NSString *)name{
    NSURLSessionDataTask *task = self.keyForTask[name];
    [task cancel];
    [self.keyForTask removeObjectForKey:name];
}

- (NSMutableDictionary*)keyForTask{
    if (!_keyForTask) {
        _keyForTask = [NSMutableDictionary dictionary];
    }
    return _keyForTask;
}

@end
